﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using MiniProject.Models;
using MiniProject.ViewModels;
using SQLite;
using Xamarin.Essentials;

namespace MiniProject.Services
{//由李伯轩完成
    /// <summary>
    /// 基金存储
    /// </summary>
    public class FundStorage:IFundStorage {
        /// <summary>
        /// 数据库文件名
        /// </summary>
        private const string DbName = "funds.sqlite3";
        /// <summary>
        /// 数据库文件路径
        /// </summary>
        public static readonly string FundDbPath =
            Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder
                    .LocalApplicationData), DbName);

        /// <summary>
        /// 数据库连接
        /// </summary>
        private SQLiteAsyncConnection _connection;

        private SQLiteAsyncConnection Connection =>
            _connection ??
            (_connection = new SQLiteAsyncConnection(FundDbPath));

        private IPreferenceStorage _preferenceStorage;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns></returns>
        public async Task InitializeAsync() {
            using (var dbFileStream = new FileStream(FundDbPath, FileMode.Create)) {
                using (var dbAssertStream = Assembly.GetExecutingAssembly()
                           .GetManifestResourceStream(DbName)) {
                    await dbAssertStream.CopyToAsync(dbFileStream);
                }
            }

            _preferenceStorage.Set(FundStorageConstants.VersionKey,FundStorageConstants.Version);
        }

        /// <summary>
        /// 判断是否已经初始化
        /// </summary>
        /// <returns></returns>
        public bool IsInitialized() =>
            _preferenceStorage.Get(FundStorageConstants.VersionKey, -1) ==
                FundStorageConstants.Version;

        /// <summary>
        /// 获取基金
        /// </summary>
        /// <param Name="code">基金代码</param>
        /// <returns></returns>
        public async Task<Fund> GetFundAsync(string code) =>
            await Connection.Table<Fund>()
                .FirstOrDefaultAsync(p => p.Code == code);
        /// <summary>
        /// 获取一组基金
        /// </summary>
        /// <param Name="where">where条件</param>
        /// <param Name="skip">跳过结果的数量</param>
        /// <param Name="take">返回结果的数量</param>
        /// <returns></returns>
        public async Task<List<Fund>> GetFundsAsync(Expression<Func<Fund, bool>> @where, int skip, int take)=>
            await Connection.Table<Fund>().Where(where).Skip(skip).Take(take)
                .ToListAsync();

        public FundStorage(IPreferenceStorage preferenceStorage) {
            _preferenceStorage = preferenceStorage;
        }

        public async Task CloseAsnyc() => await Connection.CloseAsync();
    }
}
